
led1=3
led2=4
gpio.mode(led1,gpio.OUTPUT)
gpio.mode(led2,gpio.OUTPUT)
gpio.write(led1, gpio.HIGH);
gpio.write(led2, gpio.HIGH);

print ("STA WI-FI Test...")
wifi.setmode(wifi.STATION)
cfg={}
--cfg.ssid="CMCC-dv2N"
cfg.ssid="Pluto_2.4G"
cfg.pwd="999888@@"
wifi.sta.config(cfg)
counter=0
mac=""


mytimer = tmr.create()
mytimer:register(6000,tmr.ALARM_AUTO,
function()
    if (wifi.sta.getip()==nil) then
        print("IP unavaiable,Wating...")
        counter=counter+1
        if(counter>10)then
            node.restart()
        end
    else
        print(wifi.sta.getip())
        mac=mac..string.gsub(wifi.sta.getmac(),":","")
        print(mac)
        mytimer:stop()
        mqtt_connect()
    end
end) 
mytimer:start()

--mqtt_test.lua
function mqtt_connect()
    pub_topic = "mcu_to_pc/"..mac
    sub_topic = "pc_to_mcu/"..mac
    clientId = "clientId_mqtt_"..mac
    print("connect mqtt "..clientId)
    print(pub_topic)
    print(sub_topic)
    myClient = mqtt.Client(clientId,120,"dc3","dc3")
    myClient:connect("59.36.246.11", 18083, false,
        function(client)
            print("connected")
        end,
        function(client, reason)
            print("connect failed "..reason)
            node.restart()
        end)
    myClient:lwt(pub_topic,"mcu is closed")
    myClient:on("connect",
        function(clinet)
            if (myClient:publish(pub_topic,"online",0,0)) then
                print("pc connected mcu")
            end
            if (myClient:subscribe(sub_topic,0)) then
                print("subscribe is success.")

                gpio.write(led1, gpio.LOW);
                tmr.delay(50000)
                gpio.write(led1, gpio.HIGH);

timer1 = tmr.create()
timer1:register(60000,tmr.ALARM_AUTO,
function()
    myClient:publish(pub_topic,"online",0,0)
end)
timer1:start()
                
            end
        end)
    myClient:on("offline",
        function(client)
            myClient:publish(pub_topic,"offline",0,0)
            node.restart()
        end)
    myClient:on("message",
    function(client , topic , message)
            print("get a message.\n")
            print(topic..":"..message)
                  if(message == "ON1")then
              gpio.write(led1, gpio.LOW);
              print("led1 on")
        elseif(message == "OFF1")then
              gpio.write(led1, gpio.HIGH);
            print("led1 off")
        elseif(message == "ON2")then
              gpio.write(led2, gpio.LOW);
            print("led2 on")
        elseif(message == "OFF2")then
              gpio.write(led2, gpio.HIGH);
            print("led2 off")
        end
        end)  
end      
--mqtt_close.lua
--if(myClient:close()) then
--    print("mqtt is closed.")
--else
--    print("closed is failed.")
--end
